package com.czk.zookeeper.zookeepercli.exsit;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/3 22:07
 */
public class ExsitTest {
    ZooKeeper zooKeeper = null;

    /**
     * before上创建连接
     *
     * @throws IOException
     */
    @Before
    public void before() throws IOException {
        // 由于zookeeper连接是异步的，所以需要经主线程阻塞
        CountDownLatch countDownLatch = new CountDownLatch(1);
        zooKeeper = new ZooKeeper("192.168.25.133:2181", 10000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                // 连接成功
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("连接创建成功");
                    // 释放主线程
                    countDownLatch.countDown();
                }
            }
        });
        // 阻塞主线程
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    @After
    public void after() {
        try {
            zooKeeper.close();
            System.out.println("关闭连接成功");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步获取该节点是否存在
     *
     * @throws Exception
     */
    @Test
    public void fun_1() throws Exception {
        Stat exists = zooKeeper.exists("/create", false);
        System.out.println(exists);
    }

    /**
     * 异步获取信息
     *
     * @throws Exception
     */
    @Test
    public void fun_2() throws Exception {
        zooKeeper.exists("/create", false, new AsyncCallback.StatCallback() {
            @Override
            public void processResult(int i, String s, Object o, Stat stat) {
                // 0 代表成功
                System.out.println(i);
                // 节点路径
                System.out.println(s);
                // 上下文对象
                System.out.println(o);
                // 节点的属性信息
                System.out.println(stat.getVersion());
            }
        }, "czk");
    }
}
